import java.util.ArrayList;
import java.util.List;

public class CanChange {

    public boolean canChange1(String start, String target) {
        int n = start.length();
        int m =  target.length();
        char[] c1 = start.toCharArray();
        char[] c2 = target.toCharArray();
        List<Integer> list1 = new ArrayList<>();
        List<Integer> list2 = new ArrayList<>();
        if (m != n) return false;
        StringBuilder s1 = new StringBuilder();
        StringBuilder s2 = new StringBuilder();
        for (int i = 0; i < m; i++) {
            if (c1[i] != '_') {
                s1.append(c1[i]);
                if (c1[i] == 'L') {
                    list1.add(i);
                } else list2.add(i);
            }
            if (c2[i] != '_') s2.append(c2[i]);
        }
        if (!s1.toString().equals(s2.toString())) return false;
        for (int i = 0; i < n; i++) {
            if (c2[i] == 'L' && c1[i] == '_') {
                Integer index = list1.get(0);
                list1.remove(0);
                c1[index] = '_';
                c1[i] = 'L';
            } else if (c2[i] == 'L' && c1[i] == 'L') {
                list1.remove(0);
            } else if (c1[i] == 'L' && c2[i] == '_') {
                return false;
            }
        }
        for (int i = n - 1; i >= 0; i--) {
            if (c2[i] == 'R' && c1[i] == '_') {
                Integer index = list2.get(list2.size() - 1);
                list2.remove(list2.size() - 1);
                c1[index] = '_';
                c1[i] = 'R';
            } else if (c2[i] == 'R' && c1[i] == 'R') {
                list2.remove(list2.size() - 1);
            } else if (c1[i] == 'R' && c2[i] == '_') {
                return false;
            }
        }
        return new String(c1).equals(new String(c2));
    }

    public boolean canChange(String start, String target) {
        if (!start.replaceAll("_", "").equals(target.replaceAll("_", ""))) return false;
        int l1 = 0;
        int r1 = 0;
        int l2 = 0;
        int r2 = 0;
        for (int i = 0; i < start.length(); i++) {
            char c1 = start.charAt(i);
            char c2 = target.charAt(i);
            if (c1 == 'L') {
                ++l1;
            } else if (c1 == 'R') ++r1;
            if (c2 == 'L') {
                ++l2;
            } else if (c2 == 'R') ++r2;
            if (l1 > l2 || r1 < r2) return false;
        }
        return true;
    }
}
